package com.ebay.contest.gfour.restful;

import java.util.HashMap;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ebay.contest.gfour.common.ApiResult;
import com.ebay.contest.gfour.common.ApiResultUtils;
import com.ebay.contest.gfour.common.GeoLocation;
import com.ebay.services.client.ClientConfig;
import com.ebay.services.client.FindingServiceClientFactory;
import com.ebay.services.finding.FindItemsByKeywordsRequest;
import com.ebay.services.finding.FindItemsByKeywordsResponse;
import com.ebay.services.finding.FindingServicePortType;
import com.ebay.services.finding.ItemFilter;
import com.ebay.services.finding.ItemFilterType;
import com.ebay.services.finding.PaginationInput;

@Component
@Path("/FindItemByKeywords/{keywords}")
public class FindItemsByKeywords {

    @Autowired
    ClientConfig clientConfig;

    @Autowired
    HashMap<Integer, GeoLocation> zipCodeMapper;

    FindingServicePortType serviceClient;

    private Logger logger = Logger.getLogger(FindItemsByCategory.class);

    @GET
    @Produces({ MediaType.APPLICATION_JSON })
    public Response doGet(@PathParam("keywords") String keywords) {
        if (serviceClient == null) { // create a service client
            serviceClient = FindingServiceClientFactory.getServiceClient(clientConfig);
        }

        ApiResult result = queryEbay(keywords);

        return Response.status(200).entity(result).build();
    }

    private ApiResult queryEbay(String keywords) {

        FindItemsByKeywordsRequest request = new FindItemsByKeywordsRequest();
        // set request parameters
        request.setKeywords(keywords);
        PaginationInput pi = new PaginationInput();
        pi.setEntriesPerPage(100);
        request.setPaginationInput(pi);

        // shall we use "LocatedIn" item filter to only search for a specific country?
        ItemFilter filterByCountry = new ItemFilter();
        filterByCountry.setName(ItemFilterType.LOCATED_IN);
        // http://www.iso.org/iso/country_codes/iso_3166_code_lists/country_names_and_code_elements
        filterByCountry.getValue().add("US");
        request.getItemFilter().add(filterByCountry);

        // call service
        FindItemsByKeywordsResponse response = serviceClient.findItemsByKeywords(request);
        logger.info("Find " + response.getSearchResult().getCount() + " items for keywords [" + keywords + "].");
        String stat = String.format("Category=[%s], total_pages=[%d], total_entries=[%d]", keywords, response
                .getPaginationOutput().getTotalPages(), response.getPaginationOutput().getTotalEntries());
        logger.info(stat);

        ApiResult result = ApiResultUtils.convertEbayResultToOurFormat(response.getSearchResult(), zipCodeMapper);
        result.setId(keywords);

        return result;
    }
}
